<template>
  <div>
    <el-dialog
      v-loading="loading"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :show-close="true"
      :append-to-body="true"
      :class="{'mobile-el-dialog': showMobilePage}"
      class="large-common-dialog-size add-enter-account-wrap"
      @close="closeDialog"
      @open="openDialog"
    >
      <Title title="添加核销" font-size="16px" style="margin: 0 0 16px"/>
      <div :style="{maxHeight: tableHeight+'px'}" class="dialog-scroll">
        <div :style="showMobilePage?{marginBottom: '10px'}:''" class="filter-input-box">
          <FilterInput
            v-model="filterData"
            :filter-list="filterList"
            :show-mobile-icon="showMobilePage"
            show-search-btn
            class="FilterTool"
            @handelClick="queryClick"
            @queryEmpty="queryEmpty" />
        </div>
        <div class="table-box">
          <div v-loading="listLoading" class="table-list">
            <el-table
              v-loading="listLoading"
              v-if="list.items.length > 0"
              ref="financeTable"
              :data="list.items"
              max-height="338px"
              class="fb-table"
              element-loading-text="加载中..."
              empty-text="暂无数据"
              fit
              hightlight-current-row
            >
              <el-table-column align="left" label="到账日期" min-width="110">
                <template slot-scope="scope">
                  <div>{{ scope.row.arrivalTime | standardFormat('YYYY/MM/DD') }}</div>
                </template>
              </el-table-column>
              <!-- <el-table-column align="left" label="客户名称" width="110">
              <template slot-scope="scope">{{ scope.row.customerName || '--' }}</template>
            </el-table-column> -->
              <el-table-column align="left" label="付款人名称" width="140">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.payName" />
                </template>
              </el-table-column>
              <el-table-column align="right" label="收入金额(元)" width="140">
                <template slot-scope="scope">
                  <PriceColumn :real-val="scope.row.incomeAmount" :price="returnFen(scope.row.incomeAmount)" />
                </template>
              </el-table-column>
              <el-table-column align="right" label="可核销金额(元)" width="140">
                <template slot-scope="scope">
                  <PriceColumn :real-val="scope.row.unWriteOffAmount" :price="returnFen(scope.row.unWriteOffAmount)" />
                </template>
              </el-table-column>
              <el-table-column align="left" label="该订单核销" width="100">
                <template slot-scope="scope">
                  <ToolTip :content="returnFen(scope.row.enterAccAmount)" />
                </template>
              </el-table-column>
              <el-table-column align="left" label="付款人账号" width="140">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.payNumber" />
                </template>
              </el-table-column>
              <el-table-column align="left" label="交易单号" width="140">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.transactionNumber" />
                </template>
              </el-table-column>
              <el-table-column align="left" label="类型" width="80">
                <template slot-scope="scope">{{ scope.row.flowType | flowTypeFilter }}</template>
              </el-table-column>
              <el-table-column align="left" label="流水单号" width="170">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.flowNumber" />
                </template>
              </el-table-column>
              <el-table-column align="left" label="核销状态" width="110">
                <template slot-scope="scope">{{ scope.row.verificationState | setVerificationState }}</template>
              </el-table-column>
              <el-table-column align="left" label="备注" width="110">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.remark" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="核销金额(元)" width="120" fixed="right">
                <template slot-scope="scope">
                  <div class="table-inner-input">
                    <!-- disabled：如果总可核销金额为负，那么订单的待核销金额如果是正的就不能填写， 如果总可核销金额为正的，则待核销金额如果是负的就不能填写 -->
                    <!-- :disabled="(isPositive && scope.row.unWriteOffAmount <= 0) || (!isPositive && scope.row.unWriteOffAmount > 0)" -->
                    <el-input
                      v-only-number="{max: 9999999999999999 ,min: -9999999999999, precision: 2, enableNull: true}"
                      v-model="scope.row.creditAmount"
                      type="number"
                      class="credit-amount"
                      @mousewheel.native.prevent
                      @input="getAmount(scope)"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column v-if="isShowMonth" label="业绩月份" align="center" width="120" fixed="right">
                <template slot="header">
                  <el-tooltip effect="dark" placement="top-start">
                    <div slot="content" style="max-width: 140px;">
                      以订单最后核销的流水所设置的业绩月份为准
                    </div>
                    <div class="custom-table-header">
                      <span class="name">业绩月份</span>
                      <i class="el-icon-warning-outline" />
                    </div>
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.performanceMonth"
                    :clearable="false"
                    :editable="false"
                    type="month"
                    value-format="timestamp"
                    format="yyyy/MM"
                  />
                </template>
              </el-table-column>
              <el-table-column align="left" width="80" fixed="right">
                <template slot="header">
                  <div class="custom-table-header">
                    <span class="name">操作</span>
                  </div>
                </template>
                <template slot-scope="scope">
                  <el-button
                    :loading="scope.row.loading"
                    :disabled="btnLoading"
                    type="text"
                    class="to-comfirm"
                    @click="toComfirm(scope)"
                  >确认核销</el-button>
                </template>
              </el-table-column>
            </el-table>
            <empty-placeholder v-else style="margin-bottom: 24px" />
          </div>
          <el-row type="flex" justify="end" class="pagination-area">
            <el-pagination
              v-show="list.total > 0"
              :current-page="list.page"
              :page-size="list.perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              :layout="showMobilePage?'total, prev, next, jumper':'total, prev, pager, next, sizes, jumper'"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </el-row>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Title from '@/components/Title';
import ClearBtn from '@/components/Common/ClearBtn';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import chargeOff from '@/views/finance/mixins/chargeOff';
import { verificationOptions } from '@/views/project/model/selectData';
import { setVerificationState } from '@/filters/status';
import { standardFormat } from '@/filters/date';
import { getList, writeOffFinance } from '@/api/finance';
import { paramsRangeFormat } from '@/utils/paramsFormat';
// import ElMessage from '@/utils/message';
// import { getCurrentZeroTime } from '@/utils';
import { mapState } from 'vuex';

/**
 * v3.5.1调整为侧边抽屉弹窗，该弹窗已废弃
 * */
export default {
  name: 'AddEnterAccountDialog',
  filters: {
    setVerificationState,
    standardFormat,
    flowTypeFilter(val) {
      // 流水类型。0:普通 1:对抵
      let text = '--';
      switch (val) {
        case 0:
          text = '普通';
          break;
        case 1:
          text = '对抵';
          break;
      }
      return text;
    }
  },
  components: {
    Title,
    ClearBtn,
    EmptyPlaceholder
  },
  mixins: [chargeOff],
  props: {
    orderId: {
      type: Number,
      default: null
    },
    clientId: {
      type: Number,
      default: null
    },
    isShowMonth: {
      type: Boolean,
      default: false
    },
    orderType: {
      type: Number,
      default: null
    },
    writeOffAmount: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      btnLoading: false,
      listLoading: false,
      unWriteOffAmount: 0,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true,
        totalAmount: '',
        amount: {}
      },
      perPage: 20,
      isEnterSuccess: false,
      page: 1,
      filterData: {
        clientName: ''
      },
      filterList: [
        { keyword: 'clientName', name: '付款人名称', type: 'input' },
        { keyword: 'transactionNumber', name: '交易单号', type: 'input' },
        { keyword: 'flowOrderNum', name: '流水单号', type: 'input' },
        { keyword: 'payName', name: '付款账号', type: 'input' },
        { keyword: 'remark', name: '备注', type: 'input' },
        { keyword: 'incomeAmount', name: '收入金额', type: 'inputRange' },

        { keyword: 'verificationState', name: '核销状态', type: 'select', options: verificationOptions },
        { keyword: 'flowType', name: '类型', type: 'select', labelWidth: '40px', options: [{ value: 0, label: '普通' }, { value: 1, label: '对抵' }] },
        { keyword: 'arrivalTime', name: '到账日期', type: 'rangeDate', timeType: 'daterange', format: 'yyyy/MM/dd' }
      ],
      dataOption: [{
        keyword: 'arrival',
        name: '到账日期'
      }],
      projectId: '',
      mengliOrderId: '',
      isPositive: false,
      creditAmount: null,
      tableHeight: '',
      clientName: '',
      rangeKeyArr: [{
        attr: 'arrivalTime',
        start: 'arrivalStartTime',
        end: 'arrivalEndTime',
        type: 'time'
      }, {
        attr: 'incomeAmount',
        start: 'incomeAmountStart',
        end: 'incomeAmountEnd',
        type: 'moneyFixed'
      }]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  methods: {
    handleClose() {
      this.dialogVisible = false;
      if (this.isEnterSuccess) {
        this.$emit('enterSuccess');
      }
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = JSON.parse(JSON.stringify(this.filterData));
      paramsRangeFormat(this.rangeKeyArr, params);
      params.projectId = this.projectId;
      this.listLoading = true;
      if (this.orderId && !(this.orderType || this.orderType === 0)) {
        params.orderId = this.orderId;
      } else {
        params.mengliOrderId = this.orderId;
      }
      getList(this.page, this.perPage, params).then(({ data }) => {
        this.list = data;
        this.ids = '';
        this.list.isInit = false;
        this.listLoading = false;
        if (this.setSelectRow) this.setSelectRow(data.items);
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    closeDialog() {
      this.filterData = {
        clientName: ''
      };
      this.isEnterSuccess = false;
    },
    openDialog() {
      const clientHeight = window.innerHeight;
      this.tableHeight = (clientHeight * 2) / 3;
      this.fetchData(true);
    },
    initData(data, detail) {
      const { clientName, id } = detail;
      this.unWriteOffAmount = data;
      this.clientName = clientName;
      /**
         * 如果流水的收入金额是否为正，只能核销含税金额为正的订单，且核销金额只能输入正数
         * 如果流水的收入金额是否为负或为0，只能核销含税金额为负的订单，且核销金额只能输入负数
         */
      this.isPositive = Number(this.unWriteOffAmount) > 0; // 流水的收入金额是否为正
      this.$set(this.filterData, 'clientName', clientName);
      if (!this.orderId) {
        this.projectId = id;
      }
    },
    getAmount(scope) {
      this.creditAmount = Number(scope.row.creditAmount).toFixed(2);
      const unWriteOffAmount = Math.abs(scope.row.unWriteOffAmount / 100); // 该行可核销金额
      const writeOffAmount = Math.abs(this.writeOffAmount / 100); // 该订单/流水可核销金额
      const min = writeOffAmount > unWriteOffAmount ? unWriteOffAmount : writeOffAmount;
      const max = writeOffAmount > unWriteOffAmount ? writeOffAmount : unWriteOffAmount;
      if (unWriteOffAmount === 0 || writeOffAmount === 0) {
        if (scope.row.creditAmount > 0) {
          scope.row.creditAmount = 0;
          this.creditAmount = 0;
        }
        if (scope.row.creditAmount < 0 && scope.row.creditAmount < -max) {
          scope.row.creditAmount = -max;
          this.creditAmount = -max;
        }
      } else {
        if (Number(scope.row.creditAmount) < 0) {
          scope.row.creditAmount = Number(scope.row.creditAmount) < -min ? -min : scope.row.creditAmount;
          this.creditAmount = Number(scope.row.creditAmount) < -min ? -min : scope.row.creditAmount;
        }
        if (Number(scope.row.creditAmount) > 0) {
          scope.row.creditAmount = Number(scope.row.creditAmount) > min ? min : scope.row.creditAmount;
          this.creditAmount = Number(scope.row.creditAmount) > min ? min : scope.row.creditAmount;
        }
      }

      // const flowUnWriteOffAmount = this.returnFen(scope.row.unWriteOffAmount);
      // const orderUnWriteOffAmount = this.returnFen(this.unWriteOffAmount);
      /* if (this.isPositive) {
        if (this.creditAmount < 0) {
          scope.row.creditAmount = 0;
          this.creditAmount = 0;
          return;
        }
        const min = flowUnWriteOffAmount > orderUnWriteOffAmount ? orderUnWriteOffAmount : flowUnWriteOffAmount;
        if (this.creditAmount >= min) {
          scope.row.creditAmount = min >= 0 ? min : 0;
          this.creditAmount = min >= 0 ? min : 0;
        }
      } else {
        if (Number(this.creditAmount) > 0) {
          scope.row.creditAmount = '';
          this.creditAmount = '';
          ElMessage.warning('负流水只能核销负核销金额');
        }
        const min = flowUnWriteOffAmount > orderUnWriteOffAmount && flowUnWriteOffAmount !== 0 ? flowUnWriteOffAmount : orderUnWriteOffAmount;
        if (this.creditAmount <= min) {
          scope.row.creditAmount = min || '';
          this.creditAmount = min || '';
        }
      } */
      if (scope.row.creditAmount === '') {
        return;
      }
    },
    returnFen(amount) {
      // if (amount === null) return '--';
      if (amount > 0 || amount < 0) {
        return amount / 100;
      } else {
        return 0;
      }
    },
    toComfirm(scope) {
      const { creditAmount } = scope.row;
      if (!creditAmount || Number(creditAmount) === 0) {
        this.$message({
          type: 'error',
          message: `请填写不为0的核销金额`
        });
        return;
      }
      let orderInfo;
      if (this.isShowMonth) {
        const performanceMonth = scope.row.performanceMonth.toString().slice(0, scope.row.performanceMonth.toString().length - 3);
        orderInfo = [{
          id: this.orderId,
          creditAmount: scope.row.creditAmount * 100,
          performanceMonth: Number(performanceMonth),
          type: this.orderType || this.orderType === 0 ? 2 : ''
        }];
      } else {
        orderInfo = [{
          id: this.$route.params.id,
          creditAmount: scope.row.creditAmount * 100,
          type: 1
        }];
      }
      this.btnLoading = true;
      scope.row.loading = true;
      writeOffFinance(scope.row.id, orderInfo).then(res => {
        const { code, data } = res;
        if (code === 200) {
          const { clientId, clientName } = this;
          if (data) {
            const { status } = data;
            // mixins引入是否可核销提示
            this.toAddPaymanPage(clientId, clientName, status);
          } else {
            this.$message({
              type: 'success',
              message: '核销成功'
            });
            this.fetchData();
            if (!this.isEnterSuccess) this.isEnterSuccess = true;
            this.creditAmount = null;
          }
        }
      }).catch(err => {
        console.error(err);
      }).finally(() => {
        this.btnLoading = false;
        scope.row.loading = false;
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.filterData = {
        clientName: ''
      };
      this.fetchData(true);
    }
  }
};
</script>
<style lang="scss" scoped>

.dialog-scroll {
  @include scrollBar($x: hidden, $y: auto);
}
.custom-table-header {
  display: flex;
  align-items: center;
  .name {
    display: inline-block;
    margin-right: 5px;
  }
}
.add-enter-account-wrap {
  .to-comfirm {
    &.is-disabled {
      background: #F5F7FA;
      color: #C0C4CC;
    }
  }
  .table-inner-input {
    &::v-deep {
      .el-input__inner {
        height: 28px;
      }
    }
  }
  .filter-input-box {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 24px;
  }
  .table-box {
    &::v-deep {
      .el-date-editor.el-input {
        input {
          width: 100px;
          height: 24px;
          padding-right: 12px;
          border: 1px solid #e4e4e4;
        }
        .el-input__prefix {
          .el-input__icon {
            line-height: 24px !important;
          }
        }
      }
    }
    ::v-deep .el-date-editor.el-input input {
      height: 28px;
      padding-right: 5px;
    }
  }
}
</style>
<style lang="scss">
@import '@/styles/placeholder.scss';
.el-message-box--center.charge-message-cancel .el-message-box__btns {
  @extend %el-message-box--center-el-message-box__btns !optional;
}
</style>
